package algorithm.binary;

public class Template {
    /*
    // 二分搜索框架
    int binarySearch(int[] nums, int target){
        int left = 0;
        int right = ...;
        while(...){
            int mid = left+(right-left)/2; // 防止left和right太大，直接相加会导致整型溢出
            if (nums[mid] == target){
                ...
            } else if (nums[mid] < target) {
                left = ...;
            } else if (nums[right] > target) {
                right = ...;
            }
        }
        return ...;
    }
     */
    int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }

    // 寻找左侧边界的二分搜索(示例：1,2,2,2,4寻找第一个2)
    int leftBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        // 搜索区间为[left, right]
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                // 搜索区间为[mid+1, right]
                left = mid + 1;
            } else if (nums[mid] > target) {
                //搜索区间为[left, mid-1]
                right = mid - 1;
            } else if (nums[mid] == target) {
                // 收缩右侧边界
                right = mid - 1;
            }
        }
        // 检查出界情况
        if (left >= nums.length || nums[left] != target) {
            return -1;
        }
        return left;
    }

    // 寻找右侧边界的二分搜索
    int rightBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                // 这里改成收缩左侧边界即可
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            }
        }
        // 检查边界问题
        if (right < 0 || nums[right] != target){
            return -1;
        }
        return right;
    }
}
